package com.demo;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

/**测试deleteSlice
 * @author Ziroom
 *
 */
public class DemoThread {

	private static final String PATH = "d:\\zsl\\index2";

	public static void createIndex() throws Exception {
        //1、创建一个Director对象，指定索引库保存的位置。

        //1.1把索引库保存在内存中
        //Directory directory = new RAMDirectory();

        //1.2把索引库保存在磁盘
        Directory directory = FSDirectory.open(new File(PATH).toPath());

        //2、基于Directory对象创建一个IndexWriter对象
        IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
        //当使用IKAnalyzer分词时，是如下写法。
       	//IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
        IndexWriter indexWriter = new IndexWriter(directory, config);

        Thread threadA = new Thread(() -> {
        	//3、读取磁盘上的文件，对应每个文件创建一个文档对象。
            String[] arr = new String[] {
            	"lucene lucene lucene lucene lucene lucene action",
            	"lucene"
            };
            int i=0;
            for (String str : arr) {
                //取文件名
                String fileName = "测试文件" + i++;
                //文件的内容
                String fileContent = str;
                //文件的大小
                long fileSize = str.length();

                //创建Field
                //参数1：域的名称，参数2：域的内容，参数3：是否存储
                Field fieldName = new StringField("name", fileName, Field.Store.YES);
                Field fieldContent = new TextField("content", fileContent, Field.Store.YES);

                //创建文档对象
                Document document = new Document();
                //向文档对象中添加域
                document.add(fieldName);
                document.add(fieldContent);

                //5、把文档对象写入索引库
                try {
					indexWriter.addDocument(document);
				} catch (IOException e) {
					e.printStackTrace();
				}

            }
        });
        threadA.start();

        indexWriter.deleteDocuments(new Term("content", "lucene"));

        Field fieldName = new StringField("name", "测试文件2", Field.Store.YES);
        Field fieldContent = new TextField("content", "action", Field.Store.YES);
        Document document = new Document();
        document.add(fieldName);
        document.add(fieldContent);
        indexWriter.addDocument(document);

        //6、关闭indexwriter对象
        indexWriter.close();
    }

	public static void searchIndex() throws Exception {
        //1、创建一个Director对象，指定索引库的位置
        Directory directory = FSDirectory.open(new File(PATH).toPath());
        //2、创建一个IndexReader对象
        IndexReader indexReader = DirectoryReader.open(directory);
        //3、创建一个IndexSearcher对象，构造方法中的参数indexReader对象。
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        //4、创建一个Query对象，TermQuery
        Query query = new TermQuery(new Term("content", "lucene"));
        //5、执行查询，得到一个TopDocs对象
        //参数1：查询对象 参数2：查询结果返回的最大记录数
        TopDocs topDocs = indexSearcher.search(query, 10);
        //6、取查询结果的总记录数
        System.out.println("查询总记录数：" + topDocs.totalHits);
        //7、取文档列表
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        //8、打印文档中的内容
        for (ScoreDoc doc : scoreDocs) {
            //取文档id
            int docId = doc.doc;
            //根据id取文档对象
            Document document = indexSearcher.doc(docId);
            System.out.println(document.get("name"));
            System.out.println(document.get("content"));

        }
        //9、关闭IndexReader对象
        indexReader.close();
    }

	public static void standardAnalyzer() throws Exception {
        //1.创建一个Analyzer对象，StandardAnalyzer对象
        Analyzer analyzer = new IKAnalyzer();
        //2.使用分析器对象的tokenStream方法获得一个TokenStream对象
        String text2="Lucene是apache软件基金会4 jakarta项目组的一个子项目，是一个开放源代码的全文检索引擎工具包，但它不是一个完整的全文检索引擎，而是一个全文检索引擎的架构，提供了完整的查询引擎和索引引擎，部分文本分析引擎。";
        TokenStream tokenStream = analyzer.tokenStream("", text2);
        //3.向TokenStream对象中设置一个引用，相当于数一个指针
        CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
        //4.调用TokenStream对象的rest方法。如果不调用抛异常
        tokenStream.reset();
        //5.使用while循环遍历TokenStream对象
        while (tokenStream.incrementToken()) {
            System.out.println(charTermAttribute.toString());
        }
        //6.关闭TokenStream对象
        tokenStream.close();
    }

	public static void main(String[] args) throws Exception {
		createIndex();
		searchIndex();
		//standardAnalyzer();
	}

}
